<template>
  <div class="statistics">
    <!-- 引导 -->
    <div id="statistics-guide"></div>
    <!-- 返回按钮 -->
    <div class="go-back" @click="goBack">
      <i class="iconfont icon-left1"></i>
      <span>{{ $t('common.base.back') }}</span>
    </div>
    <!-- 内容 -->
    <div v-if="!grayFlag || isShowList" class="statistics-tab">
      <div
        v-for="(item, index) in tabList"
        :key="index" class="statistics-tab-th"
        v-show="
          (item.title !== $t('report.statistics.title1') && item.title !== $t('report.statistics.title2')) ||
          (item.title === $t('report.statistics.title1') && screenMenuSwitch) ||
          (item.title === $t('report.statistics.title2') && contractGray)
        ">
        <h3 v-if="!grayFlag">{{item.title}}</h3>
        <h3 v-else-if="item.contens.length || (item.show && isAdmin)">{{item.title}}</h3>
        <div :class="{'statistics-tab-td': item.contens.length}" class="task-flex task-ai">
          <el-tooltip class="item" :open-delay="300" effect="dark" :content="v.msg" placement="top-start" v-for="(v, i) in item.contens" :key="i" :disabled="!v.msg" id="statistics-tab-td-item">
            <div class="statistics-tab-td-item task-pointer task-flex task-ai" @click="jump(v)" :class="{'statistics-icon-bj': item.title === $t('report.statistics.title1') && !grayFlag}">
              <div class="icon" :class="styles(v)"><i class="iconfont" :class="v.icon"></i></div>
              <img v-if="imgType(v.type)" class="customizes" :src="reportImage1" alt="">
              <img v-if="v.type === 'produce'" class="customizes" :src="reportImage2" alt="">
              <div :class="{'task-font24': item.title === $t('report.statistics.title1') && !grayFlag}">
                {{v.title}}
                <div v-if="item.title === $t('report.statistics.title1') && !grayFlag" class="task-font14 task-mt12">
                  <div>{{$t('report.statistics.tip1')}}；</div>
                  {{$t('report.statistics.tip2')}}
                </div>
              </div>
            </div>
          </el-tooltip>
          <div 
            v-if="(item.show && !grayFlag) || (item.show && isAdmin)" 
            v-show="is_enterpriseEdition || is_oldVipEdition" 
            class="statistics-tab-td-add task-flex task-ai task-pointer" 
            id="statistics-tab-td-add" 
            @click="jump({
              url: `/stats/customReport`, 
              type: item.show, 
              title: item.show === 'task' ? $t('report.statistics.title12') : $t('report.statistics.title13'),
              parentName: item.title
            }, item.num)"
          >
            <i class="iconfont icon-icon02"></i>
            {{item.show === 'task' ? $t('report.statistics.title12') : $t('report.statistics.title13')}}
          </div>
        </div>
      </div>
    </div>

    <!-- 无数据状态 -->
    <div class="statistics-tab" v-if="!isShowList && loadingPage && grayFlag">
      <div class="no-auth-box">
        <img :src="noAuthImg" />
        <p>{{$t('report.statistics.tip3')}}。</p>
      </div>
    </div>

    <!-- 虚拟dom -->
    <div id="dom"></div>
    <div id="statistics"></div>
  </div>
</template>
<script>
import { t } from '@src/locales';
const ssbList = {
  title: t('report.statistics.title14'),
  contens: [
    {title: t('report.statistics.title15'), icon: 'icon-signal-fill', msg: t('report.statistics.title15'), url: '/stats/business', type: 'personnel_performance'}, 
    {title: t('report.statistics.title16'), icon: 'icon-calendar-fill', msg: t('report.statistics.title16'), url: '/stats/calendar', type: 'personnel_performance_calendar'},
    {title: t('report.statistics.title17'), icon: 'icon-signal-fill', msg: t('report.statistics.title17'), url: '/stats/business', type: 'product_fault'},
    {title: t('report.statistics.title18'), icon: 'icon-signal-fill', msg: t('report.statistics.title18'), url: '/stats/business', type: 'mtbt'},
    {title: t('report.statistics.title19'), icon: 'icon-signal-fill', msg: t('report.statistics.title19'), url: '/stats/business', type: 'work_hours'},
    {title: t('report.statistics.title20'), icon: 'icon-piechart-circle-fil', msg: t('report.statistics.title20'), url: '/stats/business', type: 'service_type'},
    {title: t('report.statistics.title21'), icon: 'icon-signal-fill', msg: t('report.statistics.title21'), url: '/stats/business', type: 'cost_stat'},
  ],
}
import { getOssUrl, getLocalesOssUrl } from '@src/util/assets'
const reportImage1 = getOssUrl('/New.png')
const reportImage2 = getLocalesOssUrl('/customizes.png')// img-checked

// 系统报表数据
import { TABLIST, NOT_CONTROL } from './ReportModel';
// const REPORTLIST = [...TABLIST, ...NOT_CONTROL];
const REPORTLIST = TABLIST;
import {
  STATISTICS_GUIDE
} from '@src/component/guide/productV2Store'; // 引导存储

const noAuth = getOssUrl('/no_auth.png');
import { storageGet, storageSet } from '@src/util/storage'; // 存储方法
import { isArray } from 'lodash';

import * as ReportApi from '@src/api/ReportApi.ts';
import * as ScreenDataApi from '@src/api/ScreenDataApi';

import http from 'src/util/HttpUtil';       

// mixins
import SuperQrCodeBhAnalysis from '@src/modules/productV2/bhAnalysis/grayMixins'
import { getContractGray } from '@src/api/CustomerApi.ts'

import { isStandardEdition, isExperienceEdition, isEnterpriseEdition, isBasicEditionHideServe, isBasicEditionHideEvent, isBasicEditionHidePay, isBasicEditionHideProduct, isBasicEditionHidePart, isBasicEditionHideServiceReport, isBasicEditionControl, isBasicEditionHideCustomReport } from '@shb-lib/version'
import { useRole } from '@hooks/useRole.ts'



export default {
  name: 'statistics',
  mixins: [SuperQrCodeBhAnalysis],
  data() {
    return {
      reportImage1,
      reportImage2,
      screenMenuSwitch: false,
      tabList: [],
      is_oldVipEdition: isStandardEdition() || isExperienceEdition(),
      is_enterpriseEdition: isEnterpriseEdition(),
      menuData: [],
      isAdmin: useRole().isAdmin,
      loadingPage: false,
      grayFlag: false,
      dataScreenModel: 0,
      contractGray: false,
      isOneGrayQrCodeFlag: true // 阀门 为了不让mixins里多请求接口
    }
  },
  computed: {
    // 基础版功能是否隐藏服务
    isBasicEditionHideServe() {
      return isBasicEditionHideServe() 
    },
    // 基础版功能是否隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent() 
    },
    // 基础版功能是否隐藏支付
    isBasicEditionHidePay() {
      return isBasicEditionHidePay() 
    },
    // 基础版功能是否隐藏产品
    isBasicEditionHideProduct() {
      return isBasicEditionHideProduct() 
    },
    // 基础版功能是否隐藏备件
    isBasicEditionHidePart() {
      return isBasicEditionHidePart() 
    },
    // 基础版功能是否隐藏服务报表
    isBasicEditionHideServiceReport() {
      return isBasicEditionHideServiceReport() 
    },
    // 基础版功能是否隐藏自定义报表
    isBasicEditionHideCustomReport() {
      return isBasicEditionHideCustomReport() 
    },
    isBasicEditionControl() {
      return isBasicEditionControl() 
    },
    newTabList() {
      let tabList = this.grayFlag ? this.reportDataInfo : REPORTLIST;
      // 基础版过滤服务台报表
      if (this.isBasicEditionHideServe) {
        tabList = tabList.filter(item => item.title !== this.$t('report.statistics.title3'))
      }
      // 基础版过滤人员报表中的人员事件统计
      if (this.isBasicEditionHideEvent) {
        tabList.forEach(item => {
          if (item.title === this.$t('report.statistics.title4')) {
            item.contens = item.contens.filter(subItem => subItem.title !== this.$t('report.statistics.title5'))

            item.contens.forEach(subItem => {
              if (subItem.title === this.$t('report.statistics.title6')) {
                subItem.msg = `${this.$t('report.statistics.tip4')}。`
              }
              if (subItem.title === this.$t('report.statistics.title7')) {
                subItem.msg = `${this.$t('report.statistics.tip5')}。`
              }
              if (subItem.title === this.$t('report.statistics.title8')) {
                subItem.msg = `${this.$t('report.statistics.tip6')}。`
              }
            })
          }
        })
      }

      // 基础版过滤营收报表、人员报表中的人员营收统计
      if (this.isBasicEditionHidePay) {
        tabList = tabList.filter(item => item.title !== this.$t('report.statistics.title9'))

        tabList.forEach(item => {
          if (item.title === this.$t('report.statistics.title4')) {
            item.contens = item.contens.filter(subItem => subItem.title !== this.$t('report.statistics.title10'))

            item.contens.forEach(subItem => {
              if (subItem.title === this.$t('report.statistics.title11')) {
                subItem.msg = this.$t('report.statistics.tip7')
              }
            })
          }
        })
      }

      // 基础版过滤客户报表中的客户信息统计
      if (this.isBasicEditionControl) {
        tabList.forEach(item => {
          if (item.title === this.$t('report.statistics.title22')) {
            item.contens = item.contens.filter(subItem => subItem.title !== this.$t('report.statistics.title23'))
          }
        })
      }

      // 基础版过滤产品报表
      if (this.isBasicEditionHideProduct) {
        tabList = tabList.filter(item => item.title !== this.$t('report.statistics.title24'))
      }

      // 基础版过滤备件报表
      if (this.isBasicEditionHidePart) {
        tabList = tabList.filter(item => item.title !== this.$t('report.statistics.title25'))
      }

      // 基础版过滤备件报表
      if (this.isBasicEditionHideServiceReport) {
        tabList = tabList.filter(item => item.title !== this.$t('report.statistics.title26'))
      }

      return tabList
    },
    // 设置key
    menuMap() {
      const menuList = this.menuData
      const menuMap = {}
      
      menuList.forEach(item => {
        menuMap[item.reportKey] = item
      })
      
      return menuMap
    },
    managementReportChartListMap() {
      let chartListMap = {}

      Object.keys(this.menuMap).forEach(key => {
        let children = []
        let childrenMap = {}
        let item = {}
        
        item = this.menuMap[key]

        if (isArray(item?.reportThemeList)) {
          children = item.reportThemeList
          childrenMap = {}
          children.forEach(child => {
            childrenMap[child.reportKey] = child
          })
        }

        chartListMap[item.reportKey] = JSON.parse(JSON.stringify(childrenMap))
      })

      return chartListMap
    },
    // 筛选出有权限的页面系统数据
    reportDataInfo() {
      let arrList = [];
      for(let key in this.managementReportChartListMap){
        const currentChartMap = this.managementReportChartListMap[key] || {}
        const i = TABLIST.findIndex(x=>x.reportKey === key);

        let currentChartList = TABLIST[i]?.contens || []
        currentChartList = currentChartList.filter(item => {
          return Boolean(currentChartMap[item.reportKey])
        })

        // 自定义报表添加
        if(!this.isBasicEditionHideCustomReport){ // 基础版逻辑控制
          const customData = this.customInit(currentChartMap, TABLIST[i].title)
          if(customData.length) currentChartList = [...currentChartList, ...customData];
        }
        
        let itemInfo = TABLIST[i];
        itemInfo.contens = currentChartList;
        arrList.push(itemInfo)
      }
      // return [...arrList, ...NOT_CONTROL];
      return arrList;
    },
    // 无数据图片
    noAuthImg(){
      return noAuth;
    },
    // 无数据
    isShowList(){
      return !this.tabList.every(x => x.contens.length === 0);
    }
  },
  async mounted() {
    this.getContractGray()

    await this.getGary();
    // 获取有权限的数据
    if(this.grayFlag){ // 智能报表灰度内
      await this.getReportThemeTree();
      this.tabList = this.reportDataInfo;
    }else { // 灰度外
      this.tabList = REPORTLIST;
    }

    // 没开超级二维码行为分析灰度过滤掉
    if(!this.superQrCodeGrayFlag){
      // 过滤出不展示的报表
      this.tabList = this.filterKey(this.tabList, 'SUPERQRCODEANALYSIS', 'contens');
    }

    if (!this.isBasicEditionControl) {
      this.guide()
    }
    if(!this.grayFlag) this.config();
    if(localStorage.getItem('call_center_gray') != '1') {
      let index = this.tabList.findIndex(item => item.title == this.$t('report.statistics.title27'))
      this.tabList.splice(index, 1)
    }

    this.loadingPage = true;

    if(this.grayFlag){
      let isShowSSbReports = await http.get('/setting/ssbReportGrayFunction')
      if(isShowSSbReports.data === true){
        this.tabList.unshift(ssbList)
      }
      return
    }
    if (this.isBasicEditionHideCustomReport) {
      this.tabList = this.newTabList
    } else {
      this.getAll()
    }
    let isShowSSbReports = await http.get('/setting/ssbReportGrayFunction')
    if(isShowSSbReports.data === true){
      this.tabList.unshift(ssbList)
    }
  },
  methods:{
    imgType(type) {
      return type === 'pie-chart' || type === 'histogram' || type === 'task_success' || type === 'task_failure' || type === 'product_task' || type === 'product_info'
    },
    /* 跳转 */
    async jump({url, type, title, customId, parentName}, num) {
      if (url === '/stats/customReport' && this.is_oldVipEdition) {
        this.$platform.alert(`${this.$t('report.statistics.tip8')}！`)
        return
      }
      if (url === '/stats/customReport' && num >= 5) {
        let title = type === 'task' ? this.$t('report.statistics.tip9') : this.$t('report.statistics.tip10')
        this.$platform.alert(title)
        return
      }

      if (localStorage.getItem('staffEfficiency')) {
        localStorage.removeItem('staffEfficiency')
      }
      if (localStorage.getItem('tag')) {
        localStorage.removeItem('tag')
      }
      if (customId) {
        localStorage.setItem('customId', customId)
      }
      if(title === this.$t('report.statistics.title1')){
        // 重置数据大屏开关
        sessionStorage.removeItem('OPEN_LARGE_DATA_SCREEN_ONCE');
        const { code, data } = await ScreenDataApi.getModel()
        this.dataScreenModel = data
        if(this.dataScreenModel !== 3 ) url = '/foundation/dataScreen'
      }
      // 数据埋点不需要翻译
      window.TDAPP.onEvent(`pc：统计报表-${title}`);
      
      let customeUrl = `${url}?type=${type}&parentName=${parentName}&id=${title}`;
      let fromId = window.frameElement.getAttribute('id');
      
      this.$platform.openTab({
        id: customId ? `${type}_${customId}` : type,
        url:  url !== '/stats/customReport' ? `${url}?type=${type}` : customeUrl,
        title,
        close: true,
        fromId
      })
    },
    /* 样式 */
    styles({icon, title}) {
      let sty;
      if (icon === 'icon-shujudaping' && title === this.$t('report.statistics.title1')) {
        sty = ['task-bjf46', 'statistics-icon-shadow']
      } else if (icon === 'icon-ditu2') {
        sty = 'task-bj9f'
      } else if (icon === 'icon-piechart-circle-fil') {
        sty = 'task-bjf7'
      } else if (icon === 'icon-fund-fill') {
        sty = 'task-bjd1'
      } else if (icon === 'icon-detail-fill' || icon === 'icon-calendar-fill') {
        sty = 'task-bjc4'
      } else {
        sty = 'task-bjc2'
      }
      return sty
    },
    // 引导
    guide() {
      // if (storageGet(STATISTICS_GUIDE) && storageGet(STATISTICS_GUIDE) > 0){
      //   this.$Guide().destroy(STATISTICS_GUIDE)
      //   return
      // } 

      // this.$Guide([{
      //   content:'您好，我们对报表模块进行了改造和升级，让我们看看有哪些更新吧',
      //   haveStep: true,
      //   nowStep: 1,
      //   id: 'statistics-guide',
      //   domId: 'dom',
      //   needCover: true,
      //   finishBtn: '好',
      //   inside: true,
      //   lastFinish: true
      // }, {
      //   content:'报表布局调整，您可以在此页面看到您的全部统计报表',
      //   haveStep: true,
      //   nowStep: 2,
      //   id: 'statistics-guide',
      //   domId: 'statistics',
      //   needCover: true,
      //   finishBtn: '好',
      //   inside: true,
      //   lastFinish: true
      // }, {
      //   content:'鼠标移入报表模块，您可以查看报表的说明信息！',
      //   haveStep: true,
      //   nowStep: 3,
      //   id: 'statistics-guide',
      //   domId: 'statistics-tab-td-item',
      //   needCover: true,
      //   finishBtn: '好',
      //   lastFinish: true
      // }, {
      //   content:'您可以点击此处创建您的自定义报表哦！',
      //   haveStep: true,
      //   nowStep: 4,
      //   id: 'statistics-guide',
      //   domId: 'statistics-tab-td-add',
      //   needCover: true,
      //   finishBtn: '好',
      // }], 0, '', (e) => {
      //   return new Promise((resolve, reject) => {
      //     resolve()
      //   })
      // }).create().then(res_=>{if(res_)storageSet(STATISTICS_GUIDE, '1')})    
    },
    // 权限相关的数据
    async config() {
      const res = await ReportApi.config()
      this.screenMenuSwitch = res.screenMenuSwitch
      sessionStorage.setItem('_init_data', JSON.stringify(res))
    },
    // 获取所有的自定义报表
    async getAll() {
      const {success, result} = await ReportApi.getAll()
      if (success) {
        let data = result.map(item => {
          let icon
          switch (item.chartType) {
          case 2:
            icon = 'icon-signal-fill'
            break;
          case 3:
            icon = 'icon-fund-fill'
            break; 
          case 4:
            icon = 'icon-piechart-circle-fil'
            break;         
          default:
            icon = 'icon-detail-fill'
            break;
          }
          return {
            title: item.chartName,
            msg: item.chartDesc,
            url: '/stats/customReport',
            state: item.type,
            type: 'produce', 
            customId: item.customId,
            icon
          }
        })

        this.tabList = this.newTabList.map(item => {
          data.forEach(v => {
            item.num = item.num ? item.num : 0
            if(v.state === item.type) {
              item.contens.push(v)
              item.num += 1
            }
          })
          return item
        })
      }
    },
    // 获取展示的报表模块
    async getReportThemeTree(){
      try{
        const { code, data, msg } = await ReportApi.getReportThemeTree();
        if(code !== 200) this.$message({message: msg, type: 'error'});

        const dataList = data?.reportThemeList || [];
        let reportThemeList = dataList.filter(item => item?.reportThemeList || []);
        this.menuData = reportThemeList.filter(item => item.reportKey !== 'LARGEDATASCREEN');
      }catch(err){
        console.log(err);
      }
    },
    // 自定义数据筛选
    customInit(currenInfo, parentName){
      let data = [];
      for(let key in currenInfo){
        if(currenInfo[key]?.tenantId) data.push(currenInfo[key]);
      }

      return data.map(item => {
        let icon
        switch (item.reportIcon) {
        case 2:
          icon = 'icon-signal-fill'
          break;
        case 3:
          icon = 'icon-fund-fill'
          break; 
        case 4:
          icon = 'icon-piechart-circle-fil'
          break;         
        default:
          icon = 'icon-detail-fill'
          break;
        }
        return {
          title: item.reportName,
          msg: item.textArea,
          url: '/stats/customReport',
          type: 'produce', 
          customId: item.customId,
          parentName,
          icon
        }
      })
    },
    // 获取灰度
    async getGary(){
      try{
        const res = await ReportApi.grayFunction();
        if(res.status !== 0) return;

        this.grayFlag = res.data.dashBoardAirp;
      }catch(err){
        console.log(err);
      }
    },
    // 递归过滤
    filterKey(data, key, attr){ // 数据 被过滤的值 子列表属性名
      if(!attr) return;
      data.forEach(x => {
        if(x.reportKey === key) return;
        if(x[attr]) x[attr] = this.filterKey(x[attr], key, attr);
      });
      return data.filter(x => x.reportKey !== key);
    },
    // 返回
    goBack(){
      window.location.href = `${this.$resourcePrefix}/stats/intelligenceReport/index`;
    },
    
    // 获取合同灰度
    async getContractGray() {
      let res
      try {
        res = await getContractGray({code: 'CONTRACT'})
      } catch(err) {}
      if(res.succ) {
        this.contractGray = res.data.CONTRACT;
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.statistics {
    padding: 12px;
    position: relative;
    padding-top: 75px;
    &-tab{
        &-td {
            margin-bottom: 20px;
            &-item {
                box-shadow: rgba(0, 0, 0, 0.04) 0px 4px 10px 0px;
                &:hover{
                  box-shadow: rgba(0, 0, 0, 0.12) 0px 8px 16px 0px;
                }
                .icon {
                    width: 40px;
                    height: 40px;
                    text-align: center;
                    line-height: 40px;
                    color: #fff;
                    border-radius: 4px;
                    margin-right: 12px;
                    > i {
                      font-size: 25px;
                    }
                }
            }
            &-item, &-add {
                position: relative;
                width: 293px;
                height: 72px;
                background: #FFFFFF;
                border-radius: 4px;
                margin-right: 12px;
                margin-bottom: 12px;
                padding: 16px;
                font-size: 16px;
                line-height: 22px;
                .customizes {
                  position: absolute;
                  width: 35px;
                  top: 0;
                  right: 0;
                }
            }
            &-add {
                background-color: rgba(245, 245, 245, 1);
                border: 1px solid rgba(217, 217, 217, 1);
                .icon-icon02 {
                  color: rgba(191, 191, 191, 1);
                }
            }
        }
        .no-auth-box {
          height: 100%;
          padding-top: 50px;
          text-align: center;

          img {
            width: 160px;
            height: 160px;
            margin-bottom: 8px;
          }

          p {
            color: $text-color-regular;
          }
        }
    }
    // icon
    .icon-icon02 {
        &:before {
            font-size: 41px;
            margin-right: 5px;
            position: relative;
            top: 3px;
        }
    }
}
#dom {
  position: absolute!important;
  width: 100px;
  height: 40px;
  top: 50%;
  left: 50%;
  margin: -20px 0 0 -50px;
}
#statistics {
  position: absolute!important;
  width: 100px;
  height: 10px;
  top: 0;
  left: 100px;
}
.statistics-icon-bj{
    width: 598px;
    height: 140px;
    background: url('../../../assets/img/data-big-screen.png') no-repeat;
    background-size: 100%;
    color: #FFFFFF;
    align-items: baseline;
}
.statistics-icon-shadow{
    background-color: rgba(255, 255, 255, 0.32);
}
.statistics-tab-td-add {
  i {
    margin-right: 4px;
  }
}

.go-back {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 50px;
  padding-left: 12px;
  line-height: 50px;
  background-color: #fff;
  cursor: pointer;
}
</style>
